package com.wl.gateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author wangl
 * @desc
 * @date:2017/6/2017:39
 * @Copyright (c) 2017, DaChen All Rights Reserved.
 */
public class AccessFilter extends ZuulFilter {

    private static Logger log = LoggerFactory.getLogger(AccessFilter.class);


    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        HttpServletResponse response = ctx.getResponse();
        log.info(String.format("%s request to %s", request.getMethod(), request.getRequestURL().toString()));

        Object access_token = request.getParameter("access_token");
        if(access_token == null){
            log.warn("access token is empty");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(500);
            try {
                response.getWriter().println("{'a':'100','b':'200'}");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
        log.info("access token ok");
        return null;
    }
}
